<template>
    <el-dialog :model-value="visible" :title="isEdit ? '编辑组合' : '创建新组合'"
        @update:model-value="$emit('update:visible', $event)" width="60%" :close-on-click-modal="false">
        <el-form :model="form" ref="combinationFormRef" label-width="120px" :rules="rules">
            <el-form-item label="组合名称" prop="name">
                <el-input v-model="form.name" placeholder="请输入组合名称"></el-input>
            </el-form-item>
            <el-form-item label="风险等级" prop="riskLevel">
                <el-select v-model="form.riskLevel" placeholder="请选择风险等级">
                    <el-option label="R1-谨慎型" value="R1"></el-option>
                    <el-option label="R2-稳健型" value="R2"></el-option>
                    <el-option label="R3-平衡型" value="R3"></el-option>
                    <el-option label="R4-进取型" value="R4"></el-option>
                    <el-option label="R5-激进型" value="R5"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="策略描述" prop="strategy">
                <el-input type="textarea" v-model="form.strategy" placeholder="详细描述组合的投资策略"></el-input>
            </el-form-item>
            <el-form-item label="产品特征" prop="features">
                <el-input type="textarea" v-model="form.features" placeholder="描述组合的产品特征"></el-input>
            </el-form-item>

            <el-divider>成分基金</el-divider>

            <div v-for="(holding, index) in form.holdings" :key="index" class="holding-item">
                <el-form-item 
                    :label="'基金 ' + (index + 1)" 
                    :prop="'holdings.' + index + '.fundCode'"  
                    :rules="{ required: true, message: '必须输入基金代码', trigger: 'blur' }">
                    <el-input v-model="holding.fundCode" placeholder="输入基金代码" style="width: 45%; margin-right: 10px;"></el-input>

                    <el-input-number 
                        v-model="holding.targetRatio" 
                        :precision="4" 
                        :step="0.01" 
                        :min="0.0001" 
                        :max="1"
                        placeholder="目标比例 (如 0.25)" 
                        style="width: 45%;">
                    </el-input-number>

                    <el-button @click.prevent="removeHolding(index)" type="danger" link style="margin-left: 10px;">删除</el-button>
                </el-form-item>
            </div>

            <el-form-item>
                <el-button @click="addHolding">添加基金</el-button>
                <span style="margin-left: 20px; color: #909399;">当前总比例: {{ totalRatio.toFixed(4) }}</span>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="$emit('update:visible', false)">取消</el-button>
                <el-button type="primary" @click="submitForm">保存</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup>
import { ref, watch, reactive, computed } from 'vue';
import { ElMessage } from 'element-plus';

const props = defineProps({
    visible: Boolean,
    combinationData: Object,
});

const emit = defineEmits(['update:visible', 'saved']);

const isEdit = ref(false);
const form = ref({});
const combinationFormRef = ref(null);

const initForm = () => {
    isEdit.value = !!props.combinationData?.id;
    if (isEdit.value) {
        form.value = JSON.parse(JSON.stringify(props.combinationData));
    } else {
        // 已修改: 使用新的持仓结构进行初始化
        form.value = {
            name: '',
            riskLevel: '',
            strategy: '',
            features: '',
            holdings: [
                { fundCode: '', targetRatio: null }
            ]
        };
    }
};

const rules = reactive({
    name: [{ required: true, message: '组合名称不能为空', trigger: 'blur' }],
    riskLevel: [{ required: true, message: '请选择风险等级', trigger: 'change' }],
});

watch(() => props.visible, (newVal) => {
    if (newVal) {
        initForm();
        setTimeout(() => combinationFormRef.value?.clearValidate(), 0);
    }
});

const totalRatio = computed(() => {
    return form.value.holdings?.reduce((sum, holding) => sum + (Number(holding.targetRatio) || 0), 0) || 0;
});

const addHolding = () => {
    // 已修改: 推入新的持仓结构
    form.value.holdings.push({ fundCode: '', targetRatio: null });
}

const removeHolding = (index) => {
    form.value.holdings.splice(index, 1);
}

const submitForm = async () => {
    if (!combinationFormRef.value) return;
    await combinationFormRef.value.validate((valid) => {
        if (valid) {
            if (Math.abs(totalRatio.value - 1.0) > 0.0001) {
                ElMessage.error('所有成分基金的目标比例之和必须为 1');
                return;
            }
            emit('saved', form.value, isEdit.value);
        } else {
            ElMessage.error('请填写所有必填项');
        }
    });
};
</script>

<style scoped>
.holding-item {
    margin-bottom: 18px;
}
</style>